package com.learn.config;

import com.learn.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author WuLiangHang
 */
public class XmlConfigBuilder {

    public XmlConfigBuilder() {
    }

    public static Configuration parseConfig(InputStream in) throws DocumentException, PropertyVetoException {
        //1.读取配置文件并且塞到Configuration中
        Document document = new SAXReader().read(in);
        Element root = document.getRootElement();
        List<Element> propertyList = root.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element :
                propertyList) {
            String name = element.attribute("name").getValue();
            String value = element.attribute("value").getValue();
            properties.put(name, value);
        }
        Configuration configuration = new Configuration();
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(dataSource);

        //2.读取配置文件中的SQL 塞到MappedStatement中
        List<Element> mapperList = root.selectNodes("//mapper");
        for (Element mapper :
                mapperList) {
            String mapperPath = mapper.attribute("resource").getValue();
            XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
            xmlMapperBuilder.parse(mapperPath);
        }
        return configuration;
    }
}
